import axios from 'axios'

// 创建 axios 实例
const api = axios.create({
      baseURL: 'http://localhost:8891/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 401错误处理
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }
    
    return Promise.reject(error)
  }
)

// 获取用户角色列表
export const getUserRoles = () => {
  return api.get('/roles/')
}

// 获取角色统计信息
export const getRoleStats = () => {
  return api.get('/roles/stats')
} 